#!/usr/bin/python
# -*- coding: utf-8 -*-

#'Select name from table order by name asc'

import time
import random
import datetime
import hashlib
from threading import Thread, Lock
import threading
import pg	#python-pygresql
import sqlite3 as lite
import traceback
import encrypt




class sqliteWrite():
	def __init__(self, sqlpath):
		self.sqlpath = sqlpath
		self.mutex = Lock()

	def connect(self):
		conn = lite.connect(self.sqlpath)
		conn.row_factory = self.dict_factory
		curs = conn.cursor()  
		return [conn, curs]

	def get_restaurant_info(self, var, userDomain):
		try:
			[conn, curs] = self.connect()
			curs.execute("select " + var + " from restaurant where resname='" + userDomain + "'")
			websettings = curs.fetchall()
			websettings = websettings[0]
			conn.close()
			return websettings
		except:
			raise Exception('This restaurant ' + userDomain + ' does not exist')

	def query(self, command):
		self.mutex.acquire()
		try:
			[conn, curs] = self.connect()
			curs.execute(command)
			websettings = curs.fetchall()

			conn.close()
			return websettings
		finally:
			self.mutex.release()

	def get_restaurant_name(self):
		cmd = "select resname from server where uuid='root';"
		result = self.query(cmd)
		return result[0]['resname']

	def dict_factory(self, cursor, row):
	    d = {}
	    for idx, col in enumerate(cursor.description):
	        d[col[0]] = row[idx]
	    return d


	def updateTable(self, tableName, dataDictionary):
		successful = True
		try:
			self.mutex.acquire()
			[conn, curs] = self.connect()
	
			for i, j in dataDictionary.items():
				if type(j) == type('a') or type(j) == type(u'a'):
					tmp_name = j.replace("''","|quote|")
					tmp_name = tmp_name.replace("'", "''")
					tmp_name = tmp_name.replace("|quote|", "''")
					dataDictionary[i] = encrypt.toUTF8(tmp_name)


			curs.execute("PRAGMA table_info('" + tableName + "')")
			websettings = curs.fetchall()
			pragDic = {}
			for i in websettings:
				pragDic[ str(i['name']) ] = str(i['type'])
	
			utc_datetime = datetime.datetime.utcnow()
			dataDictionary['last_edit'] = utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
			for i, j in dataDictionary.items():
				if j == None:
					if pragDic[i] == u'number':
						dataDictionary[i] = 0
					else:
						dataDictionary[i] = ''
	
			curs.execute("select uuid from " + tableName + " where uuid='" + dataDictionary['uuid'] + "'")
			websettings = curs.fetchall()

			if len(websettings) == 0: 
				[mkeys, vals] = self.formPairs(dataDictionary)
				curs.execute("INSERT INTO " + tableName + " " + mkeys + " VALUES" + vals )
			else:
				for i, j in dataDictionary.items():
					if type(j) == type('s') or type(j) == type(u's'):
						m = j.replace("''","'")
					else:
						m = j
					curs.execute("UPDATE " + tableName + " SET " + i + "=? WHERE uuid=?", (encrypt.toUTF8(m), dataDictionary['uuid']))
	
	
			conn.commit()
		except Exception, e:
			print('Error :: ' , str(e))
			successful = False
		finally:
			conn.close()
			self.mutex.release()
			return successful



	def delete_user(self, uuid):
		try:
			self.mutex.acquire()
			[conn, curs] = self.connect()
			curs.execute("DELETE FROM users where uuid='" + uuid + "'")
			conn.commit()
		finally:
			conn.close()
			self.mutex.release()


	def deleteSubChoice(self, subchoice_uuid):
		try:
			self.mutex.acquire()
			[conn, curs] = self.connect()

			curs.execute("DELETE FROM menu where uuid='" + subchoice_uuid + "'")
			conn.commit()
		finally:
			conn.close()
			self.mutex.release()


	def deleteSubOption(self, suboption_uuid):
		try:
			self.mutex.acquire()
			[conn, curs] = self.connect()

			curs.execute("DELETE FROM menu where suboption_uuid='" + suboption_uuid + "'")
			curs.execute("DELETE FROM menu where uuid='" + suboption_uuid + "'")
			conn.commit()
		finally:
			conn.close()
			self.mutex.release()


	def delete_choices(self, choice_uuid):
		try:
			self.mutex.acquire()
			[conn, curs] = self.connect()
			#curs.execute("DELETE FROM menu where type='category' or type='item'")

			curs.execute("DELETE FROM menu where choice_uuid='" + choice_uuid + "'")
			curs.execute("DELETE FROM menu where uuid='" + choice_uuid + "'")
			conn.commit()
		finally:
			conn.close()
			self.mutex.release()




	def delete_options(self, option_uuid):
		try:
			self.mutex.acquire()
			[conn, curs] = self.connect()
			#curs.execute("DELETE FROM menu where type='category' or type='item'")

			curs.execute("DELETE FROM menu where option_uuid='" + option_uuid + "'")
			curs.execute("DELETE FROM menu where uuid='" + option_uuid + "'")
			conn.commit()
		finally:
			conn.close()
			self.mutex.release()



	def delete_dishes(self, dish_uuid):
		try:
			self.mutex.acquire()
			[conn, curs] = self.connect()
			#curs.execute("DELETE FROM menu where type='category' or type='item'")

			curs.execute("DELETE FROM menu where dish_uuid='" + dish_uuid + "'")
			curs.execute("DELETE FROM menu where uuid='" + dish_uuid + "'")
			conn.commit()
		finally:
			conn.close()
			self.mutex.release()


	def delete_menu(self, menu_uuid):
		try:
			self.mutex.acquire()
			[conn, curs] = self.connect()
			#curs.execute("DELETE FROM menu where type='category' or type='item'")

			curs.execute("DELETE FROM menu where menu_uuid='" + menu_uuid + "'")
			curs.execute("DELETE FROM menu where uuid='" + menu_uuid + "'")
			conn.commit()
		finally:
			conn.close()
			self.mutex.release()




	def delete_category(self, category_id):
		try:
			self.mutex.acquire()
			[conn, curs] = self.connect()
			#curs.execute("DELETE FROM menu where type='category' or type='item'")

			curs.execute("DELETE FROM menu where category_uuid='" + category_id + "'")
			curs.execute("DELETE FROM menu where uuid='" + category_id + "'")
			conn.commit()
		finally:
			conn.close()
			self.mutex.release()


	def delete_category_and_dishes(self, parent_uuid):
		try:
			self.mutex.acquire()
			[conn, curs] = self.connect()
			#curs.execute("DELETE FROM menu where type='category' or type='item'")
			curs.execute("DELETE FROM menu where (type='category' or type='item') and menu_uuid='" + parent_uuid + "'")
			conn.commit()
		finally:
			conn.close()
			self.mutex.release()


#	def delete_menu(self):
#		try:
#			self.mutex.acquire()
#			[conn, curs] = self.connect()
#			curs.execute("DELETE FROM menu where type='menu'")
#			conn.commit()
#		finally:
#			conn.close()
#			self.mutex.release()


	def formPairs(self, dataDictionary):
		akeys = '('
		for i in dataDictionary.keys():
			akeys += "'" + i + "',"
		akeys += ')'
		akeys = akeys.replace(',)',')')

		aVal = '('
		for i in dataDictionary.values():
			aVal += "'" + unicode(i) + "',"
		aVal += ')'
		aVal = aVal.replace(',)',')')
		return [akeys, aVal]


#	def delete_entire_table(self, tableName):
#		entire_menu = self.query("select uuid from " + tableName)
#		for i in entire_menu:
#			i['uuid']
















#	def singleCommand(self):
#		[conn, curs] = self.connect()
#
#		curs.execute("PRAGMA table_info('res_dat')")
#		websettings = curs.fetchall()
#
#		conn.close()
#	
#
#	#This is not a mutex protected function, should only be called indirectly within mutex
#	def getPrimaryKey(self, tableName):
#		[conn, curs] = self.connect()
#
#		curs.execute("PRAGMA table_info('" + tableName + "')")
#		websettings = curs.fetchall()
#		for i in websettings:
#			if i['pk'] == 1:
#				return i['name']
#
#		conn.close()
#		return None
#
#	def uuid(self):
#		t = long( time.time() * 1000 )
#		r = long( random.random()*100000000000000000L )
#		try:
#			a = socket.gethostbyname( socket.gethostname() )
#		except:
#			# if we can't get a network address, just imagine one
#			a = random.random()*100000000000000000L
#		data = str(t)+' '+str(r)+' '+str(a)+' '
#		data = hashlib.md5(data).hexdigest()
#		return data
#
#	def toUTF8(self, obj):
#		if type(obj) == type('h'):
#			return unicode(obj,'utf-8')
#		elif type(obj) == type(True):
#			return int(obj)
#		else:
#			return obj
#
#
#	def insertTable(self, tableName, dataDictionary):
#		if tableName == 'res_dat' or tableName == 'restaurant_users':
#			self.AlsoUpdateMainDB(tableName, dataDictionary,'insert')
#
#		self.crashReportOpen('insertTable')
#		self.mutex.acquire()
#		try:
#			[conn, curs] = self.connect()
#
#			utc_datetime = datetime.datetime.utcnow()
#			dataDictionary['last_edit'] = utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
#
#			if 'order_detail' in dataDictionary:
#				dataDictionary['order_detail'] = dataDictionary['order_detail'].replace("'", "''")
#
#			[akeys, aVal] = self.formPairs(dataDictionary)
#
#			curs.execute("""INSERT INTO """ + tableName + " " + akeys + """ VALUES""" + aVal)
#			conn.commit()
#		finally:
#			conn.close()
#			self.mutex.release()
#
#		self.crashReportClose('insertTable')
#
#	def close(self):
#		pass
#
#	def getResInfo(self, var, userDomain):
#		try:
#			[conn, curs] = self.connect()
#			curs.execute("select " + var + " from restaurant where resname='" + userDomain + "'")
#			websettings = curs.fetchall()
#			websettings = websettings[0]
#			conn.close()
#			return websettings
#		except:
#			raise Exception('This restaurant ' + userDomain + ' does not exist')
#
#
#	def crashReportOpen(self, fname):
#		pass
#		#print('-----------sqlite open---------   ' + fname)
#
#	def crashReportClose(self, fname):
#		pass
#		#print('-----------sqlite close---------   ' + fname)
#
#	def delete(self, tableName, dataDictionary):
#		self.crashReportOpen('delete')
#
#		try:
#			if tableName == 'res_dat' or tableName == 'restaurant_users' or tableName == 'meis':
#				self.AlsoUpdateMainDB(tableName, dataDictionary, 'delete')
#
#			self.mutex.acquire()
#			pKey = self.getPrimaryKey(tableName)
#
#			[conn, curs] = self.connect()
#
#			curs.execute("DELETE FROM " + tableName + " WHERE " + str(pKey) + "='" + dataDictionary[pKey] + "'")
#			conn.commit()
#			#curs.execute("DELETE FROM " + tableName + " WHERE resname='meis'")
#		finally:
#			conn.close()
#			self.mutex.release()
#
#		self.crashReportClose('delete')
#
#
#	def addColumn(self, tableName, columnName, typeString):
#		self.crashReportOpen('addColumn')
#		self.mutex.acquire()
#		try:
#			[conn, curs] = self.connect()
#			curs.execute("alter table " + tableName + " add column " + columnName + " " + typeString)
#			por = self.psqlConnection.query(cmd)
#		finally:
#			conn.close()
#			self.mutex.release()
#
#		self.crashReportClose('addColumn')
#
#	def updateTable(self, tableName, dataDictionary, alsoUpdateRemote=True):
#
#		self.crashReportOpen('updateTable')
#		retVal = True
#		try:
#			if alsoUpdateRemote:
#				if tableName == 'res_dat' or tableName == 'restaurant_users' or  tableName == 'meis':
#					self.AlsoUpdateMainDB(tableName, dataDictionary, 'update')
#	
#			self.mutex.acquire()
#			pKey = self.getPrimaryKey(tableName)
#			[conn, curs] = self.connect()
#	
#			curs.execute("PRAGMA table_info('" + tableName + "')")
#			websettings = curs.fetchall()
#			pragDic = {}
#			for i in websettings:
#				pragDic[ str(i['name']) ] = str(i['type'])
#	
#			utc_datetime = datetime.datetime.utcnow()
#			dataDictionary['last_edit'] = utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
#			for i, j in dataDictionary.items():
#				if j == None:
#					if pragDic[i] == u'number':
#						dataDictionary[i] = 0
#					else:
#						dataDictionary[i] = ''
#	
#			curs.execute("select " + pKey + " from " + tableName + " where " + pKey + "='" + dataDictionary[pKey] + "'")
#			websettings = curs.fetchall()
#			if 'order_detail' in dataDictionary:
#				dataDictionary['order_detail'] = dataDictionary['order_detail'].replace("'", "''")
#
#			if len(websettings) == 0: 
#				[mkeys, vals] = self.formPairs(dataDictionary)
#				curs.execute("INSERT INTO " + tableName + " " + mkeys + " VALUES" + vals )
#			else:
#				for i, j in dataDictionary.items():
#					curs.execute("UPDATE " + tableName + " SET " + i + "=? WHERE " + pKey + "=?", (self.toUTF8(j), dataDictionary[pKey]))
#	
#	
#			conn.commit()
#			self.crashReportClose('updateTable')
#		except Exception, e:
#			print('Error :: ' , str(e))
#			retVal = False
#		finally:
#			conn.close()
#			self.mutex.release()
#			return retVal
#
#
#	def itemExists(self, tableName, orderUUID):
#		self.mutex.acquire()
#		try:
#			pKey = self.getPrimaryKey(tableName)
#
#			[conn, curs] = self.connect()
#			curs.execute("select " + pKey + " from " + tableName + " where " + pKey + "='" + orderUUID + "'")
#			websettings = curs.fetchall()
#			conn.close()
#			if len(websettings) == 0: return False
#			else: return True
#		finally:
#			self.mutex.release()
#
#			
#	def getUserVal(self, resname, username, val):
#		self.crashReportOpen('getUserVal')
#
#		cmd = "select " + val + " from restaurant_users where "
#		cmd += "resname='" + resname + "' and "
#		cmd += "user_name='" + username.strip() + "';"
#		cmd = str(cmd)
#	
#		val = self.query(cmd)
#		val = val[0]
#		self.crashReportClose('getUserVal')
#		return val
#
#	def getUser(self, resname, username):
#		self.crashReportOpen('getUser')
#
#		cmd = "select * from restaurant_users where "
#		cmd += "resname='" + resname + "' and "
#		cmd += "user_name='" + username + "';"
#		try:
#			#conn.reset()
#			vv2 = self.query(cmd)[0]
#			self.crashReportClose('getUser')
#		
#			return vv2
#		except:
#			b = {}
#			b['rand_key'] = 'expired'
#			self.crashReportClose('getUser')
#			return b
#
#	def getAllUsersVal(self, resname, val):
#		self.crashReportOpen('getAllUsersVal')
#
#		cmd = "select " + val + " from restaurant_users where "
#		cmd += "resname='" + resname + "';"
#		self.crashReportClose('getAllUsersVal')
#		return self.query(cmd)
#
#	def getAllUsers(self, resname):
#		self.crashReportOpen('getAllUsers')
#
#		cmd = "select user_name, access from restaurant_users where "
#		cmd += "resname='" + resname + "' and access<>'root';"
#
#		self.crashReportClose('getAllUsers')
#		return self.query(cmd)
#
#
#	def getAllManagerOrders(self, resName, today):
#		self.crashReportOpen('getAllManagerOrders')
#
#		cmd = "select * from meis where "
#		cmd += "date='" + today + "' and "
#		cmd += "resname='" + resName + "'"
#		cmd += " order by order_id desc;"
#
#		self.crashReportClose('getAllManagerOrders')
#		return self.query(cmd)
#
#
#	def getAllWaiterOrders(self, resName, today, waiterName):
#		self.crashReportOpen('getAllWaiterOrders')
#
#		cmd = "select * from meis where "
#		cmd += "date='" + today + "' and "
#		cmd += "(entry_by='" + waiterName + "' or extra_info='" + waiterName + "' or status='kiosk-request') and "
#		cmd += "resname='" + resName + "'"
#		cmd += " order by order_id desc;"
#
#		self.crashReportClose('getAllWaiterOrders')
#		return self.query(cmd)
#
#	def getCurrentOrderID(self, resname, today):
#		self.crashReportOpen('getCurrentOrderID')
#
#		cmd = "select order_id from meis where "
#		cmd += "resname='" + resname + "' and "
#		cmd += "date='" + today + "' order by order_id desc;"
#		result = self.query(cmd)
#		self.crashReportClose('getCurrentOrderID')
#
#		if len(result) == 0: return 0
#		else: return result[0]['order_id']
#
#
#	def getAllDayOrders(self, resName, today):
#		self.crashReportOpen('getAllDayOrders')
#
#		cmd = "select * from meis where "
#		cmd += "date='" + today + "' and "
#		cmd += "resname='" + resName + "' and status<>'customer_login'"
#		cmd += " order by order_id desc"
#		cmd += ";"
#		result = self.query(cmd)
#
#		self.crashReportClose('getAllDayOrders')
#		return result
#
#	def getOrder(self, tableName, orderUUID):
#		try:
#			self.crashReportOpen('getOrder')
#
#			cmd = "select * from meis where "
#			cmd += "uuid='" + orderUUID + "';"
#			vvs = self.query(cmd)[0]
#
#			self.crashReportClose('getOrder')
#			return vvs
#		except:
#			return {}
#		
#
#	def getConfirmOrder(self, tableName, orderUUID):
#		try:
#			self.crashReportOpen('getConfirmOrder')
#
#			cmd = "select uuid, resname, status from meis where "
#			cmd += "confirm_uuid='" + orderUUID + "';"
#			vvs = self.query(cmd)[0]
#
#			self.crashReportClose('getConfirmOrder')
#			return vvs
#		except:
#			return {}
#
#	def getAllOrderInfoToday(self, today):
#		self.crashReportOpen('getAllOrderInfoToday')
#
#		cmd = "select * from meis where "
#		cmd += "date='" + today + "' and "
#		cmd += "submit_source_type<>'unknown';"
#		val = self.query(cmd)
#
#		self.crashReportClose('getAllOrderInfoToday')
#		return val
#
#
#	def getAllOrdersToday(self, today):
#		self.crashReportOpen('getAllOrdersToday')
#
#		cmd = "select order_detail from meis where "
#		cmd += "date='" + today + "' and "
#		cmd += "submit_source_type<>'unknown';"
#		val = self.query(cmd)
#
#		self.crashReportClose('getAllOrdersToday')
#		return val
#
#	def getRestaurantInfo(self, stuff, resName):
#		self.crashReportOpen('getRestaurantInfo')
#
#		cmd = "select " + stuff + " from res_dat where resname='" + resName + "';"
#		result = self.query(cmd)
#	
#		self.crashReportClose('getRestaurantInfo')
#
#		if len(result) == 0: return {}
#		else: return result[0]



#
#	def deleteAllOrders(self):
#		self.crashReportOpen('deleteAllOrders')
#
#		cmd = "select * from meis;"
#		val = self.query(cmd)
#		for p in val:
#			self.psqlConnection.delete('meis', p)
#
#		self.crashReportClose('deleteAllOrders')
#
#	def deleteEmptyOrders(self):
#		self.crashReportOpen('deleteEmptyOrders')
#
#		cmd = "delete from meis where status='customer_login';"
#		val = conn.query(cmd)
#
#		self.crashReportClose('deleteEmptyOrders')
#
#
#
#	def addUser(self, userData):
#		self.crashReportOpen('addUser')
#
#		mutex.acquire()
#		try:
#			self.psqlConnection.insert('restaurant_users', userData)
#		finally:
#			mutex.release()
#
#		self.crashReportClose('addUser')
#
#
#	def getAllOrdersTodayByRestaurant(self, today, resname):
#		self.crashReportOpen('getAllOrdersToday')
#
#		cmd = "select order_detail from meis where "
#		cmd += "date='" + today + "' and resname='" + resname + "' and "
#		cmd += "submit_source_type<>'unknown';"
#		val = self.query(cmd)
#
#		self.crashReportClose('getAllOrdersToday')
#		return val
#
#
#	def deleteTodayFailedOrder(self, today):
#		self.crashReportOpen('deleteTodayFailedOrder')
#
#		cmd = "select * from meis where "
#		cmd += "date='" + today + "' and "
#		cmd += "submit_source_type='unknown';"
#		val = self.query(cmd)
#		for p in val:
#			self.psqlConnection.delete('meis', p)
#
#		self.crashReportClose('deleteTodayFailedOrder')
#
#	def deleteAllFailedOrder(self, today):
#		self.crashReportOpen('deleteAllFailedOrder')
#
#		cmd = "select * from meis where "
#		cmd += "date<>'" + today + "' and "
#		cmd += "submit_source_type='unknown';"
#		val = self.query(cmd)
#		for p in val:
#			self.psqlConnection.delete('meis', p)
#
#		self.crashReportClose('deleteAllFailedOrder')
#
#	def getAllPricePerDay(self, resName, today):
#		self.crashReportOpen('getAllPricePerDay')
#
#		cmd = "select price from meis where "
#		cmd += "date='" + today + "' and status<>'customer_login' and status<>'temporary' and "
#		cmd += "resname='" + resName + "'"
#		cmd += " order by order_id desc"
#		cmd += ";"
#		#conn.reset()
#		result = conn.query(cmd)
#
#		self.crashReportClose('getAllPricePerDay')
#		return result.getresult()
#
#	def getAllNeedReviewOrders(self, resName):
#		self.crashReportOpen('getAllDayOrders')
#
#		cmd = "select * from meis where "
#		cmd += "resname='" + resName + "' and ("
#		cmd += "status='charged' or status='cash takeout')"
#		cmd += " order by order_id asc"
#		cmd += ";"
#		result = self.query(cmd)
#
#		self.crashReportClose('getAllDayOrders')
#		return result
#
#
#
#	def getAccount(self, resname, email):
#		self.crashReportOpen('getAccount')
#
#		cmd = "select * from customer_accounts where "
#		cmd += "resname='" + resname + "' and "
#		cmd += "email='" + email + "';"
#
#		result = self.query(cmd)
#
#		self.crashReportClose('getAccount')
#		if len(result) == 0: return {}
#		else: return result[0]
#
#
#








	def initialize(self):
		pass
		
		#curs.execute("DROP TABLE IF EXISTS yumbery")
		#curs.execute("CREATE TABLE yumbery ( uuid text primary key, account_name text, stripe_test_public_key text, stripe_test_private_key text, stripe_live_public_key text, stripe_live_private_key text, live_mode boolean, website text, account_password text, gmail_password text, gmail text, service_rate real DEFAULT 0.041, stripe_client_id text DEFAULT '')")



		#curs.execute("DROP TABLE IF EXISTS customer_accounts")
		#curs.execute("CREATE TABLE customer_accounts ( uuid text primary key, customer_id text, resname text, password text, restaurant_credit real DEFAULT 0, email text, phone_num text DEFAULT '', customer_name text DEFAULT '', street_num text DEFAULT '', street_name text DEFAULT '', apartment_info text DEFAULT '', address_town text DEFAULT '', address_state text DEFAULT '', street_type text DEFAULT '')")




		#curs.execute("DROP TABLE IF EXISTS restaurant_users")
		#curs.execute("CREATE TABLE restaurant_users ( uuid TEXT primary key, user_name TEXT, password TEXT, rand_key TEXT, access TEXT, resname TEXT, waiter_menu_type TEXT, manager_counting integer DEFAULT 0, waiter_font_size integer DEFAULT 30, waiter_column integer DEFAULT 2, waiter_language TEXT DEFAULT 'english', waiter_padding integer DEFAULT 20, x_swipe_threshold integer DEFAULT 100, y_swipe_threshold integer DEFAULT 200, dish_row_num integer DEFAULT 1, swipe_angle integer DEFAULT 20, swipe_allowed TEXT DEFAULT 'yes')")



		#curs.execute("CREATE TABLE meis ( uuid TEXT primary key, date TEXT, address TEXT, entry_by TEXT, hour_string TEXT, table_description TEXT, status TEXT, submit_source_type TEXT, menutype TEXT, tip REAL, email TEXT, delivery_charge REAL, extra_info TEXT, food_sum REAL, food_tax REAL, pre_calculated_price REAL, order_id integer, delivery_range integer, delivery_cost_per_mile REAL, price REAL, resname TEXT, order_detail text, expect_time TEXT, phone TEXT, customer_name TEXT, original_host TEXT, ip_addr TEXT, extra_wait_time integer, avg_takeout_wait integer, avg_delivery_wait integer, token_id TEXT, last_four_digits TEXT, stripe_charge_id TEXT, stripe_charge_description TEXT, stripe_livemode integer, stripe_charge_fee REAL, stripe_currency TEXT, stripe_refunded integer, stripe_card_type TEXT, stripe_cvc_check TEXT, credit_reduction REAL DEFAULT 0, refunded REAL DEFAULT 0, browser_type TEXT DEFAULT '', field_dat TEXT DEFAULT '', pn_reference TEXT DEFAULT '', invoice_num TEXT DEFAULT '')")

		#curs.execute("DROP TABLE IF EXISTS meis")

		#curs.execute("CREATE TABLE meis ( uuid TEXT primary key, date TEXT, address TEXT, entry_by TEXT, hour_string TEXT, table_description TEXT, status TEXT, submit_source_type TEXT, menutype TEXT, tip REAL, email TEXT, delivery_charge REAL, extra_info TEXT, food_sum REAL, food_tax REAL, pre_calculated_price REAL, order_id integer, delivery_range integer, delivery_cost_per_mile REAL, price REAL, resname TEXT, order_detail text, expect_time TEXT, phone TEXT, customer_name TEXT, original_host TEXT, ip_addr TEXT, extra_wait_time integer, avg_takeout_wait integer, avg_delivery_wait integer, token_id TEXT, last_four_digits TEXT, stripe_charge_id TEXT, stripe_charge_description TEXT, stripe_livemode integer, stripe_charge_fee REAL, stripe_currency TEXT, stripe_refunded integer, stripe_card_type TEXT, stripe_cvc_check TEXT, credit_reduction REAL DEFAULT 0, refunded REAL DEFAULT 0, browser_type TEXT DEFAULT '', field_dat TEXT DEFAULT '', pn_reference TEXT DEFAULT '', invoice_num TEXT DEFAULT '')")

		#curs.execute("DROP TABLE IF EXISTS res_dat")
		#curs.execute("CREATE TABLE res_dat ( resname TEXT primary key, max_delivery_order real, min_delivery_order real, max_takeout_order real, min_takeout_order real, delivery_option text, takeout_wait integer, delivery_wait integer, loop_time integer, delivery_range real, allow_cash text, disable_dish_options text, tax_rate real, alphebetical_dish text, takeout_column_num integer, delivery_cost_per_mile real, delivery_allow_coupon text, disable_option_reason text, allow_point_system boolean, direct_printing boolean, cash_password text, delivery_towns text, payment_option text, payment_site text, takeoutorder_by_pass text, monday text, tuesday text, wednesday text, thursday text, friday text, saturday text, sunday text, gmail_password text DEFAULT 'meisfood', gmail text, stripe_test_public_key text, stripe_test_private_key text, stripe_live_public_key text, stripe_live_private_key text, live_mode boolean, restaurant_main_site text, temp text, discount_rate real, account_state text, account_password text, customer_id text, account_email text, customer_name text, uuid text, date text, token text, receive_order_mode text, restaurant_address text, phone_string text, front_description_1 text, front_description_2 text, setting_language text, category_font_size text, auto_confirm boolean, image_menu boolean, description_color_code text, dish_font_color_code text, image_auto_shadow boolean, home_link text, hour_link text, order_online text, menu_link text, location_link text, home_mobil text, hour_mobil text, order_online_mobil text, menu_mobil text, location_mobil text, vertical_orientation boolean, template_id text, link_bg_style text, link_bg_width text, link_bg_height text, link_table_x text, link_table_y text, background_color text, logo_width integer, logo_height integer, front_image_width integer, front_image_height integer, also_email_restaurant boolean DEFAULT false, fax_number text DEFAULT '', logo_img_link text DEFAULT 'logo.png', delivery_states text DEFAULT '', front_img text DEFAULT 'yfront_image.png', monday_takeout_start integer DEFAULT 0, tuesday_takeout_start integer DEFAULT 0, wednesday_takeout_start integer DEFAULT 0, thursday_takeout_start integer DEFAULT 0, friday_takeout_start integer DEFAULT 0, saturday_takeout_start integer DEFAULT 0, sunday_takeout_start integer DEFAULT 0, monday_takeout_end integer DEFAULT 0, tuesday_takeout_end integer DEFAULT 0, wednesday_takeout_end integer DEFAULT 0, thursday_takeout_end integer DEFAULT 0, friday_takeout_end integer DEFAULT 0, saturday_takeout_end integer DEFAULT 0, sunday_takeout_end integer DEFAULT 0, monday_delivery_start integer DEFAULT 0, tuesday_delivery_start integer DEFAULT 0, wednesday_delivery_start integer DEFAULT 0, thursday_delivery_start integer DEFAULT 0, friday_delivery_start integer DEFAULT 0, saturday_delivery_start integer DEFAULT 0, sunday_delivery_start integer DEFAULT 0, monday_delivery_end integer DEFAULT 0, tuesday_delivery_end integer DEFAULT 0, wednesday_delivery_end integer DEFAULT 0, thursday_delivery_end integer DEFAULT 0, friday_delivery_end integer DEFAULT 0, saturday_delivery_end integer DEFAULT 0, sunday_delivery_end integer DEFAULT 0, enable_fax boolean DEFAULT false, monday_start integer DEFAULT 0, tuesday_start integer DEFAULT 0, wednesday_start integer DEFAULT 0, thursday_start integer DEFAULT 0, friday_start integer DEFAULT 0, saturday_start integer DEFAULT 0, sunday_start integer DEFAULT 0, monday_end integer DEFAULT 0, tuesday_end integer DEFAULT 0, wednesday_end integer DEFAULT 0, thursday_end integer DEFAULT 0, friday_end integer DEFAULT 0, saturday_end integer DEFAULT 0, sunday_end integer DEFAULT 0, time_zone text DEFAULT 'US/Eastern', manager_alive smallint DEFAULT 0, random_threshold smallint DEFAULT 0, email_only boolean DEFAULT false, server_name text DEFAULT '', manager_site text DEFAULT 'http://manager.yummytakeouts.com/cpLogin?resName=yourDomainNameHere', update_required text DEFAULT '', server_updated text DEFAULT '', fee_percentage real DEFAULT 0.04, stripe_refresh_token text DEFAULT '', link_only_site boolean DEFAULT false, link_only_return_site text DEFAULT '', body_font_color text DEFAULT '#ffffff', executable_uuid text, exe_printing boolean DEFAULT false, zip_codes text DEFAULT '', mobile_category_column_num integer DEFAULT 2, long real, lat real, restaurant_login_token text)")


		#curs.execute("""INSERT INTO "yumbery" VALUES('abcdefghi', 'chieh', 'pk_fihG7W4bLKgobzDxzac9UV0W6VfQN', 'QaSP9xG0JyBSTUxHfC9PbUHr71icyWPR', 'pk_cu3U86WONIOCaSH6b5yJbSqnoj1KI', 'bmATARszvYEacoXtle6ZaUsFbpzhRtoc', 1, 'http://yummytakeouts.com', 'wadazilao', '72chiehnkim', 'yummytakeouts@gmail.com', 0.041, 'ca_HGeaRCmuSRY5nBsnY72rJWrfpMl9o4dp')""")


		#curs.execute("""INSERT INTO "res_dat" VALUES('meis',200.0,16.0,200.0,10.0,'Delivery on',18,35,9,3.0,'yes','no',0.09,'no',7,1.0,'no','',1,0,'meis','Pembroke,Allenstown,Hooksett','','https://secure.yummytakeouts.com','bypass','closed','','','11:15''] = AM''] = to''] = 9''] = PM','','','','meisfood','suncookmeis@gmail.com','pk_G1YhHqPXKUBXT8BCrvBQC2DV2JJAU','Hip2kOLmQtFYcs8efr9fpviuBwQfn02j','pk_GzMVAFjbRN7R4Fu8gXZmgbOtvgkvS','1sjI1LWwKl6D5ervUusMaI3zlDaguJvz',1,'http://meisrestaurant.com/meis','TVoOTBdfhN',0.03,'activated','mirespass','cus_isbQXWasg8TGsf','','','c09c5e69e60b2a1aa3043123b1721d8c','','','web','','','','','chinese','14',1,0,'#761414','#fffff0',1,'','','','','','','','','','',0,'C','','900','50','100','0','#380009',200,70,300,300,0,'','logo.png','NH','yfront_image.png',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,'US/Eastern',60,0,0,'manager4','http://manager.yummytakeouts.com/cpLogin?resName=yourDomainNameHere','','39221,43478,51414,51967,28250,43171,5400,8080',0.04,'',0,'','#ffffff','',0,'03275,03106',2,-71.4527,43.1308,'')""")
		mdat = {}
		mdat["delivery_allow_coupon"] = """no"""
		mdat["vertical_orientation"] = """t"""
		mdat["mobile_category_column_num"] = 2
		mdat["link_bg_width"] = """"""
		mdat["allow_cash"] = """yes"""
		mdat["sunday_end"] = 1260
		mdat["fee_percentage"] = 0.041
		mdat["discount_rate"] = 0.03
		mdat["tuesday_takeout_end"] = 1260
		mdat["uuid"] = None
		mdat["server_name"] = """secmanager4"""
		mdat["friday_delivery_start"] = 680
		mdat["hour_link"] = """<a href="/hours?resname=yourDomainNameHere">Hours</a>"""
		mdat["allow_point_system"] = """t"""
		mdat["thursday"] = """11:20 am to 9:0 pm"""
		mdat["min_delivery_order"] = 16.0
		mdat["logo_img_link"] = """cramb.png"""
		mdat["alphebetical_dish"] = """no"""
		mdat["menu_link"] = """<a href="/viewMenu?resName=yourDomainNameHere">Menu</a>"""
		mdat["auto_confirm"] = """t"""
		mdat["executable_uuid"] = """6f934ca920eafba3eb7ef6448921349e"""
		mdat["logo_height"] = 70
		mdat["fax_number"] = """8889597240"""
		mdat["monday_start"] = 0
		mdat["friday_takeout_start"] = 680
		mdat["thursday_delivery_end"] = 1260
		mdat["exe_printing"] = """f"""
		mdat["order_online_mobil"] = """<a href='/orderOnline?resName=yourDomainNameHere'><img src='html/img/order_online_mobil.png' BORDER=0 alt='' width='mswitch' height='mswitch'/></a>"""
		mdat["link_bg_height"] = """"""
		mdat["wednesday"] = """11:20 am to 9:0 pm"""
		mdat["friday_start"] = 680
		mdat["token"] = None
		mdat["tuesday_delivery_start"] = 680
		mdat["sunday_start"] = 680
		mdat["disable_option_reason"] = """Due to the volume today, we are unable to provide special options, or alter the dish."""
		mdat["delivery_towns"] = """Pembroke,Allenstown,Hooksett"""
		mdat["menu_mobil"] = """<a href="/viewMenu?resName=yourDomainNameHere"><img src="http://iamar.net/yummy/menu_mobil.png"  BORDER=0 alt="" width="mswitch" height="mswitch"/></a>"""
		mdat["monday_takeout_end"] = 0
		mdat["friday_delivery_end"] = 1320
		mdat["saturday"] = """11:20 am to 10:0 pm"""
		mdat["gmail"] = """yummytakeouts@gmail.com"""
		mdat["payment_option"] = """both cash and credit card"""
		mdat["thursday_delivery_start"] = 680
		mdat["logo_width"] = 200
		mdat["takeout_column_num"] = 7
		mdat["stripe_refresh_token"] = """"""
		mdat["account_state"] = """activated"""
		mdat["tuesday_start"] = 680
		mdat["friday_end"] = 1320
		mdat["receive_order_mode"] = """application"""
		mdat["live_mode"] = """f"""
		mdat["customer_id"] = None
		mdat["takeout_wait"] = 14
		mdat["restaurant_login_token"] = """"""
		mdat["front_description_1"] = """You can place your restaurant's introduction on this page. Below is an example of what you can say: <br><br>"""
		mdat["front_description_2"] = """Always welcomed by warm smiles and a lot of good food, Mei's Restaurant is a place where  the waitstaff will know you by your first name and you will feel like family.  The owners, Mei and Chi Wu, have been in the fine dining business for over 20 years and Chef Chi's 35  years of culinary experience will be love at first taste when you try the scrumptious items on our fairly priced menu.  This family-friendly restaurant is perfect for anybody who enjoys good food, good friends, and good company. We hope to see you soon hihisdf"""
		mdat["image_menu"] = """f"""
		mdat["stripe_live_public_key"] = """pk_5mFQFLDcnadoKO6JRYWfA7OMPuEbl"""
		mdat["friday"] = """11:20 am to 10:0 pm"""
		mdat["tax_rate"] = 0.09
		mdat["front_image_height"] = 300
		mdat["disable_dish_options"] = """no"""
		mdat["monday_delivery_end"] = 0
		mdat["thursday_takeout_end"] = 1260
		mdat["time_zone"] = """US/Eastern"""
		mdat["link_only_site"] = """f"""
		mdat["wednesday_delivery_end"] = 1260
		mdat["front_image_width"] = 300
		mdat["wednesday_end"] = 1260
		mdat["order_online"] = """<a href='/orderOnline?resName=yourDomainNameHere'>Order Online</a>"""
		mdat["setting_language"] = """chinese"""
		mdat["tuesday"] = """11:20 am to 9:0 pm"""
		mdat["wednesday_takeout_start"] = 680
		mdat["thursday_start"] = 680
		mdat["delivery_cost_per_mile"] = 2.0
		mdat["body_font_color"] = """#ffffff"""
		mdat["front_img"] = """yfront_image.png"""
		mdat["long"] = -71.4527
		mdat["wednesday_start"] = 680
		mdat["home_mobil"] = """<a href="/mobilHome?resname=yourDomainNameHere"> <img src="http://iamar.net/yummy/home_mobil.png"  BORDER=0 alt="" width="mswitch" height="mswitch"/> </a>"""
		mdat["background_color"] = """#380009"""
		mdat["delivery_wait"] = 40
		mdat["wednesday_delivery_start"] = 680
		mdat["customer_name"] = """yourname"""
		mdat["wednesday_takeout_end"] = 1260
		mdat["hour_mobil"] = """<a href="/hours?resname=yourDomainNameHere"><img src="http://iamar.net/yummy/hours_mobil.png" BORDER=0 alt="" width="mswitch" height="mswitch"/></a>"""
		mdat["manager_site"] = """http://manage.yummytakeouts.com/cpLogin?resName=yourDomainNameHere"""
		mdat["update_required"] = """download menu"""
		mdat["also_email_restaurant"] = """f"""
		mdat["saturday_delivery_end"] = 1320
		mdat["link_table_x"] = """0"""
		mdat["link_table_y"] = """0"""
		mdat["max_delivery_order"] = 200.0
		mdat["cash_password"] = """yummy"""
		mdat["thursday_takeout_start"] = 680
		mdat["restaurant_address"] = """117 Main St Suncook, NH 03275"""
		mdat["saturday_end"] = 1320
		mdat["stripe_test_public_key"] = """pk_D9U5sUtK1n17aTw1tHu0ukluGsMPu"""
		mdat["direct_printing"] = """f"""
		mdat["monday_delivery_start"] = 0
		mdat["enable_fax"] = """f"""
		mdat["sunday_takeout_end"] = 1260
		mdat["link_only_return_site"] = """"""
		mdat["temp"] = """ScQmVKs2QJ"""
		mdat["delivery_range"] = 3.0
		mdat["restaurant_main_site"] = """http://yummytakeouts.com/yourDomainNameHere"""
		mdat["stripe_test_private_key"] = """ns5msF4v1V8q9R9BWp1QQm8E77H9qjzL"""
		mdat["home_link"] = """<a href="/yourDomainNameHere">Home</a>"""
		mdat["account_password"] = """yummypass"""
		mdat["template_id"] = """"""
		mdat["delivery_option"] = """Delivery on"""
		mdat["email_only"] = """f"""
		mdat["sunday_delivery_start"] = 680
		mdat["tuesday_takeout_start"] = 680
		mdat["dish_font_color_code"] = """#FFFFF0"""
		mdat["category_font_size"] = """14"""
		mdat["sunday_takeout_start"] = 680
		mdat["thursday_end"] = 1260
		mdat["server_updated"] = """43478,39221,51414,51967,43171,28250,5400,8080"""
		mdat["tuesday_delivery_end"] = 1260
		mdat["monday_takeout_start"] = 0
		mdat["sunday_delivery_end"] = 1260
		mdat["sunday"] = """11:20 am to 9:0 pm"""
		mdat["zip_codes"] = """"""
		mdat["saturday_takeout_start"] = 680
		mdat["image_auto_shadow"] = """f"""
		mdat["payment_site"] = """https://securepayment.yummytakeouts.com"""
		mdat["account_email"] = """juliusctw@gmail.com"""
		mdat["monday"] = """Closed"""
		mdat["loop_time"] = 15
		mdat["gmail_password"] = """72chiehnkim"""
		mdat["resname"] = """yourdomainnamehere"""
		mdat["saturday_delivery_start"] = 680
		mdat["location_link"] = """<a href="/location?resname=yourDomainNameHere">Location</a>"""
		mdat["date"] = None
		mdat["saturday_start"] = 680
		mdat["lat"] = 43.1308
		mdat["phone_string"] = """(603) xxx-3532<br>(603) 333-1234"""
		mdat["takeoutorder_by_pass"] = """yummy"""
		mdat["friday_takeout_end"] = 1320
		mdat["manager_alive"] = 0
		mdat["stripe_live_private_key"] = """UySfZg9OHO8nlS8HgBvpqZspBPQE8CVL"""
		mdat["saturday_takeout_end"] = 1320
		mdat["max_takeout_order"] = 200.0
		mdat["link_bg_style"] = """"""
		mdat["tuesday_end"] = 1260
		mdat["min_takeout_order"] = 10.0
		mdat["random_threshold"] = 0
		mdat["description_color_code"] = """#EBE4C0"""
		mdat["location_mobil"] = """<a href="/location?resname=yourDomainNameHere"><img src="http://iamar.net/yummy/location_mobil.png"  BORDER=0 alt="" width="mswitch" height="mswitch"/></a>"""
		mdat["monday_end"] = 0
		mdat["delivery_states"] = """NH"""

		self.updateTable('res_dat', mdat)
		#curs.execute('INSERT INTO "res_dat" (resname) VALUES("yourdomainnamehere")')

		conn.commit()


